<?php
namespace app\common\model;
use app\common\service\MailSer;
use think\model\concern\SoftDelete;
use think\Paginator;

class EmailLogsModel extends BaseModel
{
    use SoftDelete;
    protected $table = 'email_logs';

//    protected $json = ['req_data'];



    /**
     * 获取列表
     * @param array  $input_data
     * @throws
     * @return Paginator
     * */
    public static function getPageData(array $input_data = [])
    {
        $limit = $input_data['limit']??null;
        $where=[];
        if(app()->http->getName()!='admin'){
            $where[] = ['status','=',1];
        }
        !empty($input_data['rec_email']) && $where[] = ['rec_email','like',"%".$input_data['rec_email']."%"];
        !empty($input_data['body']) && $where[] = ['body','like',"%".$input_data['body']."%"];
        !empty($input_data['keyword']) && $where[] = ['req_data','like',"%".$input_data['keyword']."%"];

        //事件范围查询
        if(!empty($input_data['search_date']) && is_array($input_data['search_date']) && count($input_data['search_date'])==2){
            $input_data['start_date'] = $input_data['search_date'][0];
            $input_data['end_date'] = $input_data['search_date'][1];
        }
        //按时间查询
        $start_date = empty($input_data['start_date'])?'':trim($input_data['start_date']);
        $start_time = empty($start_date)?'':strtotime($start_date);
        $end_date = empty($input_data['end_date'])?'':trim($input_data['end_date']);
        $end__time = empty($end_date)?'':strtotime('+1 day',strtotime($end_date));
        if(!empty($start_time) && !empty($end__time)){
            $where[] = ['create_time','>=',$start_time];
            $where[] = ['create_time','<=',$end__time];
        }elseif(!empty($start_time)){
            $where[] = ['create_time','>=',$start_time];
        }elseif(!empty($end__time)){
            $where[] = ['create_time','<=',$end__time];
        }

        return self::where($where)->order('id desc')->paginate($limit);
    }


    public static function send(array $input_data = [])
    {
        $tid = $input_data['tid']??'';
        $mode= $input_data['mode']??'';
        $order_id= $input_data['order_id']??'';
        $rec_mail = $input_data['rec_mail']??'';
        $body = $input_data['body']??'';
        $send_time = $input_data['send_time']??null;
        $host =  SysSettingModel::getContent('email', 'host');
        if(empty($rec_mail)) throw new \Exception('rec_mail必须传入');
        if(empty($body)) throw new \Exception('body必须有内容');

//        unset($input_data['rec_mail'],$input_data['body'],$input_data['host']);

        (new self())->actionAdd([
            'tid'=>$tid,
            'mode'=>$mode,
            'order_id'=>$order_id,
            'host'=>$host,
            'ip'=>request()->ip(),
            'rec_email'=>$rec_mail,
            'send_email'=>SysSettingModel::getContent('email','email'),
            'body'=>$body,
            'send_time'=>$send_time,
            'req_data'=> json_encode($input_data,JSON_UNESCAPED_UNICODE),
        ]);

        //发送邮件
        self::sendEmail();

    }

    public static function sendEmail()
    {
        self::where(['status'=>0])->where(function($query){
            $query->whereOr([
                ['send_time','=',null],
                ['send_time','<=',date('Y-m-d H:i:s')],
            ]);
        })->select()->each(function($item){
            try{
//            dump(request()->host(),request()->header('host'),request());exit;
                $req_data = $item['req_data']??'';
                $input_data = empty($req_data)?[]:json_decode($req_data,true);
                $result = MailSer::send($item['rec_email'] , $item['body'],$input_data);
            }catch (\Exception $e){
                $result = $e->getMessage();
            }
            $item->setAttr('status',1);
            $item->setAttr('handle_time',date('Y-m-d H:i:s'));
            $item->setAttr('result',$result);
            $item->save();
        });
    }




}